package com.kai.admin.security.handler;

import com.kai.admin.data.SourceUser;
import com.kai.admin.security.service.SecurityTokenService;
import com.kai.common.data.Result;
import com.kai.common.util.IpAddressUtil;
import com.kai.common.util.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 登录成功处理程序
 * </p>
 *
 * @author weijk
 * @since 2023/7/13
 */
@Slf4j
@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    @Autowired
    private SecurityTokenService securityTokenService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        SourceUser sourceUser = (SourceUser) authentication.getPrincipal();
        String accessToken = securityTokenService.generateAndSaveToken(sourceUser);

        String ip = IpAddressUtil.get(httpServletRequest);
        log.info("登录成功, url=[{}], ip=[{}], uid:[{}], name:[{}], token:[{}]", httpServletRequest.getRequestURI(), ip, sourceUser.getUserId(), sourceUser.getUsername(), accessToken);

        WebUtil.writeJson(Result.success(accessToken), httpServletResponse);
    }
}
